<?php
class BdApiModel
{
    public $chnId;
    public $syncCnt; //批量同步数量

    public function __construct(){
        $this->chnId = 2;

        $this->syncCnt = 40;
    }
    /*
        添加店铺信息
        params
            store_id 药店id
            store_name 药店名称
            start_time 开始时间
            end_time 结束时间
    */
    public function addStoreInfo($store_id = 0, $store_name = '', $start_time = '', $end_time = '')
    {
        $storeInfo = $this->getStoreInfoById($store_id); //获取药店信息

        if(empty($storeInfo)){
            $res = array(
                "errNo" => "1001"
            );
            return $res;
        }

        $storeInfo['ShortCaption'] = $store_name;

        $baseInfo = $this->setBaseInfo($storeInfo); //药店基础信息
        $cityInfo = $this->setCityInfo($storeInfo); //药店地址信息
        $businessTime = $this->setBusinessTime($start_time, $end_time); //药店营业时间
        $category = $this->getCategorys(); //获取经营范围
        $extended = $this->getExtendedInfo(); //获取扩展参数

        $regionPoint = $this->getRegionPoint($storeInfo['AID']); //获取配送区域经纬度

        $regionInfo = $this->setRegionInfo($cityInfo, $regionPoint); //配送区域信息


        $BaiDuStoreSvc = new BaiDuStoreSvc();

        $addStoreInfoData = $BaiDuStoreSvc->addShopInfo(
            $baseInfo, 
            $cityInfo, 
            $businessTime, 
            $category, 
            $extended, 
            $regionInfo
        );

        $res = $BaiDuStoreSvc->sendAddShopInfo($addStoreInfoData);
        
        if($res['errno'] == "0"){
            $shop_id = $res['data']['baidu_shop_id'];

            $addStore = $this->addChannelStoreInfo(
                $this->chnId, $store_id, $shop_id,
                $storeInfo['ShortCaption'], $storeInfo['Memo'],
                $start_time, $end_time ,
                1
            );

            return $addStore;
        }else{
            $res = array(
                "errNo" => "2001",
                "data" => $res
            );
            return $res;
        }
    }

    /*
        获取药店信息
        params
            store_id 药店id
    */
    public function getStoreInfoById($store_id = 0)
    {
        $StoreModel = new StoreModel();

        return $StoreModel->getStoreInfoById($store_id);
    }

    /*
        商户开业
        params
            store_id 店铺id
    */
    public function openShop($store_id = 0)
    {
        $BaiDuStoreSvc = new BaiDuStoreSvc();

        $data = $BaiDuStoreSvc->openShop($store_id);

        $res = $BaiDuStoreSvc->sendOpenShop($data);


        if($res['errno'] == "0"){
            $open = updateChannelStoreStatus($this->chnId, $store_id, 1);

            return $open;
        }else{
            $res = array(
                "errNo" => "2006",
                "data" => $res
            );
            return $res;
        }
    }

    /*
        商户歇业
        params
            store_id 店铺id
    */
    public function closeShop($store_id = 0)
    {
        $BaiDuStoreSvc = new BaiDuStoreSvc();

        $data = $BaiDuStoreSvc->closeShop($store_id);

        $res = $BaiDuStoreSvc->sendCloseShop($data);


        if($res['errno'] == "0"){
            $open = updateChannelStoreStatus($this->chnId, $store_id, 0);

            return $open;
        }else{
            $res = array(
                "errNo" => "2006",
                "data" => $res
            );
            return $res;
        }
    }

    /*
        商户下线
        params
            store_id 店铺id
    */
    public function offlineShop($store_id = 0)
    {
        $BaiDuStoreSvc = new BaiDuStoreSvc();

        $data = $BaiDuStoreSvc->offlineShop($store_id);

        $res = $BaiDuStoreSvc->sendOfflineShop($data);


        if($res['errno'] == "0"){
            $open = updateChannelStoreStatus($this->chnId, $store_id, 2);

            return $open;
        }else{
            $res = array(
                "errNo" => "2006",
                "data" => $res
            );
            return $res;
        }
    }

    /*
        更新店铺公告
        params
            store_id 店铺id
            topic 公告信息
    */
    public function setShopTopic($store_id = 0, $topic = '')
    {
        $BaiDuStoreSvc = new BaiDuStoreSvc();

        $data = $BaiDuStoreSvc->setShopTopic($store_id, $topic);

        $res = $BaiDuStoreSvc->sendSetShopTopic($data);

        if($res['errno'] == "0"){
            $save = updateChannelStoreTopic($this->chnId, $store_id, $topic);

            return $save;
        }else{
            $res = array(
                "errNo" => "2007",
                "data" => $res
            );
            return $res;
        }
    }

    /*
        设置药店基础信息
        params
            store_info 药店信息对象
    */
    public function setBaseInfo($store_info = array())
    {
        $BaiDuStoreSvc = new BaiDuStoreSvc();

        $shop_id = $store_info['ID'];
        $name = $store_info['ShortCaption'];
        $shop_logo = $GLOBALS['SHOP_LOGO'];
        $phone = $store_info['Tel'];
        $service_phone = $store_info['STel'];

        $baseInfo = $BaiDuStoreSvc->setBaseInfo($shop_id, $name, $shop_logo, $phone, $service_phone);

        return $baseInfo;
    }

    /*
        设置药店城市信息
        params
            store_info 药店信息对象
    */
    public function setCityInfo($store_info = array())
    {
        $BaiDuStoreSvc = new BaiDuStoreSvc();

        //防止数据库中有错误经纬度信息 所以进行转换
        $point = getPointLocation($store_info['JinDuX'], $store_info['WeiDuY']);

        $cityInfo = getCityInfoByPoint($point['lng'], $point['lat']);

        $province = $cityInfo['province'];
        $city = $cityInfo['city'];
        $county = $cityInfo['district'];
        $address = $store_info['Address'];

        $lng = $point['lng'];
        $lat = $point['lat'];
        $cityInfo = $BaiDuStoreSvc->setCityInfo($province, $city, $county, $address, $lng, $lat);


        return $cityInfo;
    }

    /*
        设置营业时间
        params
            start_time 开始时间 秒数
            end_time 结束时间 秒数
    */
    public function setBusinessTime($start_time = 0, $end_time = 0)
    {
        $start_time = date("H:i", $start_time + strtotime('00:00:00'));
        $end_time = date("H:i", $end_time + strtotime('00:00:00'));

        $BaiDuStoreSvc = new BaiDuStoreSvc();

        $businessTime = $BaiDuStoreSvc->setBusinessTime($start_time, $end_time);

        return $businessTime;
    }

    /*
        获取药店经营范围
        params

    */
    public function getCategorys()
    {
        $BaiDuStoreSvc = new BaiDuStoreSvc();

        return $BaiDuStoreSvc->getCategorys();
    }

    /*
        获取扩展参数
        params

    */
    public function getExtendedInfo()
    {
        $BaiDuStoreSvc = new BaiDuStoreSvc();

        return $BaiDuStoreSvc->getExtendedInfo();
    }

    /*
        获取药店配送范围
        params
            area_id 配送区域id
    */
    public function getRegionPoint($area_id = 0)
    {    
        $StoreModel = new StoreModel();
        $BaiDuStoreSvc = new BaiDuStoreSvc();

        $areaPoint = $StoreModel->getAreaPointByAreaId($area_id);

        $res = array();

        foreach ($areaPoint as $key => $value) {
            $point = getPointLocation($value['JinDuX'], $value['WeiDuY']);

            $res[] = $BaiDuStoreSvc->setRegionPoint($point['lng'], $point['lat']);
        }

        return $res;
    }

    /*
        配送区域信息
        params
            city_info 城市信息对象
            region_point 配送区域经纬度
    */
    public function setRegionInfo($city_info = array(), $region_point = array())
    {
        $BaiDuStoreSvc = new BaiDuStoreSvc();

        $city = $city_info['city']; 
        $county = $city_info['county'];


        $delivery_time = 60;
        $delivery_fee = 0;

        $regionInfo = $BaiDuStoreSvc->setRegionInfo($city, $county, $delivery_time, $delivery_fee, $region_point);

        return $regionInfo;
    }

    /*
        添加第三方店铺信息
        params
            channel_id 第三方渠道id
            store_id 快方药店id
            shop_id 第三方店铺id
            shop_name 第三方店铺名称
            shop_desc 第三方店铺描述
            start_time 营业开始时间
            end_time 营业结束时间
            store_status 店铺状态
    */
    public function addChannelStoreInfo(
        $channel_id = 0, $store_id = 0, $shop_id = 0, 
        $shop_name = "", $shop_desc = "", 
        $start_time = 0, $end_time = 0,
        $store_status = 0
    ){
        $ChannelStoreModel = new ChannelStoreModel();

        $res = $ChannelStoreModel->addChannelStoreInfo(
            $channel_id, $store_id, $shop_id, 
            $shop_name, $shop_desc, 
            $start_time, $end_time,
            $store_status
        );

        return $res;
    }


    /*
        开通自定义分类
        params
            store_id 店铺id
    */
    public function openCategory($store_id = 0)
    {
        $BaiDuCategorySvc = new BaiDuCategorySvc();

        $data = $BaiDuCategorySvc->openCategory($store_id);

        $res = $BaiDuCategorySvc->sendOpenCategory($data);

        if($res['errno'] == "0"){
            return true;
        }else{
            $res = array(
                "errNo" => "4001",
                "data" => $res
            );
            return $res;
        }
    }

    /*
        关闭自定义分类
        params
            store_id 店铺id
    */
    public function closeCategory($store_id = 0)
    {
        $BaiDuCategorySvc = new BaiDuCategorySvc();

        $data = $BaiDuCategorySvc->closeCategory($store_id);

        $res = $BaiDuCategorySvc->sendCloseCategory($data);

        if($res['errno'] == "0"){
            return true;
        }else{
            $res = array(
                "errNo" => "4002",
                "data" => $res
            );
            return $res;
        }
    }

    /*
        初始化自定义分类
        params
            store_id 店铺id
    */
    public function initCategoryInfo($store_id = '')
    {
        $defaultCategory = $GLOBALS['defaultCategory'];

        foreach ($defaultCategory as $key => $value) {
            $this->addCategoryInfo($store_id, $key, $value, 1);
        }

        return true;
    }

    /*
        添加自定义分类
        params
            store_id 店铺id
            category_id 本地分类id

            other_category_name 第三方分类名称
            other_category_rank 第三方分类排序
    */
    public function addCategoryInfo($store_id = 0, $category_id = '', $other_category_name = '', $other_category_rank = 0)
    {
        $BaiDuCategorySvc = new BaiDuCategorySvc();

        $parent_category_id = 0;

        $data = $BaiDuCategorySvc->addCategory($store_id, $parent_category_id, $other_category_name, $other_category_rank);
        $res = $BaiDuCategorySvc->sendAddCategory($data);
        
        if($res['errno'] == "0"){

            $other_category_id = $res['data']['category_id'];

            $addCategory = addChannelCategoryInfo($this->chnId, $store_id, $category_id, $other_category_id, $other_category_name, $other_category_rank);

            return $addCategory;
        }else{
            $res = array(
                "errNo" => "2002",
                "data" => $res
            );
            return $res;
        }
    }

    /*
        更新自定义分类信息
        params
            store_id 店铺id
            other_category_id 第三方分类ID
            other_category_name 第三方分类名称
            other_category_rank 第三方分类排序

    */
    public function updateCategoryInfo($store_id = 0, $other_category_id = 0, $other_category_name = '', $other_category_rank = 0)
    {
        $BaiDuCategorySvc = new BaiDuCategorySvc();

        $categoryInfo = getOtherInfoByOtherCategoryId($other_category_id);

        $data = $BaiDuCategorySvc->updateCategory($store_id, $other_category_id, $other_category_name, $other_category_rank);

        //如果相同名称更新信息 百度会提示错误 所以 名称不变更的情况下 不提交
        if($data['name'] == $categoryInfo['other_category_name']){
            unset($data['name']);
        }

        $res = $BaiDuCategorySvc->sendUpdateCategory($data);

        if($res['errno'] == "0"){
            $save = updateChannelCategoryInfo($other_category_id, $other_category_name, $other_category_rank);

            return $save;
        }else{
            $res = array(
                "errNo" => "2003",
                "data" => $res
            );
            return $res;
        }
    }

    /*
        获取第三方分类信息
        params
            store_id 店铺id
    */
    public function getOtherCategoryByBd($store_id = 0)
    {
        $BaiDuCategorySvc = new BaiDuCategorySvc();

        $data = $BaiDuCategorySvc->getCategory($store_id);

        $res = $BaiDuCategorySvc->sendGetCategory($data);

        if($res['errno'] == "0"){
            return $res['data']['categorys'];
        }else{
            $res = array(
                "errNo" => "2004",
                "data" => $res
            );
            return $res;
        }
    }

    /*
        删除第三方分类信息
        params
            store_id 店铺id
            other_category_id 第三方分类id
    */
    public function delCategoryInfo($store_id = '', $other_category_id = '')
    {
        $BaiDuCategorySvc = new BaiDuCategorySvc();

        $data = $BaiDuCategorySvc->delCategory($store_id, $other_category_id);

        $res = $BaiDuCategorySvc->sendDelCategory($data);

        if($res['errno'] == "0"){
            $del = delChannelCategoryInfo($this->chnId, $store_id, $other_category_id);

            return $del;
        }else{
            $res = array(
                "errNo" => "2005",
                "data" => $res
            );
            return $res;
        }
    }

    
    /*
        添加商品信息
        params
            store_id 店铺id
            product_id 快方商品id
            other_category_id 第三方分类id
    */
    public function addProduct($store_id = 0, $product_id = 0, $other_category_id = 0)
    {
        $productInfo = getProductInfoById($product_id);

        if(empty($productInfo)){
            $res = array(
                "errNo" => "3001"
            );

            return $res;
        }

        $upc = $productInfo['BarCode'];
        $name = $productInfo['Caption'];
        $status = 1;
        $desc = $productInfo['ShortMemo'];
        $sale_price = intval($productInfo['LSJG'] * 100);

        $photo = $this->createPhoto($productInfo);

        $thumb = array();

        foreach ($photo as $key => $value) {
            $thumb[] = $value['url'];
        }
        $BaiDuProductSvc = new BaiDuProductSvc();

        $data = $BaiDuProductSvc->addProduct($store_id, $upc, $name, $status, $desc, $sale_price, $photo);

        $res = $BaiDuProductSvc->sendAddProduct($data);

        if($res['errno'] == "0"){
            $other_product_id = $res['data']['sku_id'];
            $add = addChannelProductInfo($this->chnId, $store_id, $product_id, $other_category_id, $other_product_id, $sale_price, $thumb);

            sleep(2);
            $bind = $BaiDuProductSvc->bindCategory($store_id, $other_product_id, $other_category_id);
             $BaiDuProductSvc->sendBindCategory($bind);

            return $add;
        }else{
            $res = array(
                "errNo" => "2010",
                "data" => $res
            );
            return $res;
        }
        
    }

    /*
        商品上线
        params
            store_id 店铺id
            product_id 商品id
    */
    public function onlineProduct($store_id = 0, $product_id = 0)
    {
        $productInfo = getChannelProductInfo($this->chnId, $store_id, $product_id);

        if(empty($productInfo)){
            $res = array(
                "errNo" => "3001"
            );
            return $res;
        }

        $BaiDuProductSvc = new BaiDuProductSvc();

        $data = $BaiDuProductSvc->onlineProduct($store_id, $productInfo['other_product_id']);
        $res = $BaiDuProductSvc->sendOnlineProduct($data);

        if($res['errno'] == "0"){
            $save = updateChannelProductStatus($this->chnId, $store_id, $product_id, 1);

            return $save;
        }else{
            $res = array(
                "errNo" => "2012",
                "data" => $res
            );

            return $res;
        }
    }

    /*
        商品下线
        params
            store_id 店铺id
            product_id 商品id
    */
    public function offlineProduct($store_id = 0, $product_id = 0)
    {
        $productInfo = getChannelProductInfo($this->chnId, $store_id, $product_id);

        if(empty($productInfo)){
            $res = array(
                "errNo" => "3001"
            );
            return $res;
        }

        $BaiDuProductSvc = new BaiDuProductSvc();

        $data = $BaiDuProductSvc->offlineProduct($store_id, $productInfo['other_product_id']);
        $res = $BaiDuProductSvc->sendOfflineProduct($data);

        if($res['errno'] == "0"){
            $save = updateChannelProductStatus($this->chnId, $store_id, $product_id, 2);

            return $save;
        }else{
            $res = array(
                "errNo" => "2011",
                "data" => $res
            );

            return $res;
        }
    }

    /*
        同步商品库存信息
        params
            data 商品库存信息
    */
    public function syncStock($data = array())
    {
        $other_shop_id = array();
        $new_data = array();

        foreach ($data as $key => $value) {
            $other_shop_id = getOtherShopIdByRedis($this->chnId, $value['store_id']);

            $new_data[$other_shop_id][] = $value;

        }

        $Dao = M("kfsy_channel_store.kf_channel_product");
        $Dao->startTrans();
        
        foreach ($new_data as $key => $value) {
            
            foreach ($value as $k => $v) {
                $updateStock = updateChannelProductStock($this->chnId, $v['store_id'], $v['other_product_id'], array('product_stock' => $v['product_stock']));

                if($updateStock == false){
                    $Dao->rollback();
                    unset($value[$k]);
                    continue;
                }
            }
            
            $postData = array();
            foreach ($value as $k1 => $v1) {
                $postData[$k1] = $v1['other_product_id'].':'.$v1['product_stock'];
            }

            $res = $this->updateStockBatch($key, $postData);

            if($res['errno'] == '0'){
                $Dao->commit();
            }else
            {
                $Dao->rollback();
                return false;
            }

        }
            
        return true;
    }

    /*
        批量同步库存信息
        params
            other_shop_id 店铺id
            stock 库存信息对象
    */
    public function updateStockBatch($other_shop_id = 0, $stock = array())
    {
        $BaiDuProductSvc = new BaiDuProductSvc();

        $stock = implode(";", $stock);
        $data = $BaiDuProductSvc->updateStockBatch($other_shop_id, $stock);

        $res = $BaiDuProductSvc->sendUpdateStockBatch($data);

        return $res;
    }

    /*
        同步商品价格信息
        params
            data 商品价格信息
    */
    public function syncPrice($data = array())
    {
        // $data = array(
        //     array(
        //          'store_id' => 3,   
        //          'other_product_id' => 11111,
        //          'product_price' => 1800   
        //     ),
        //     array(
        //          'store_id' => 3,   
        //          'other_product_id' => 1286433385,
        //          'product_price' => 1800   
        //     ),
        // );
        $other_shop_id = array();
        $new_data = array();

        foreach ($data as $key => $value) {
            $other_shop_id = getOtherShopIdByRedis($this->chnId, $value['store_id']);

            $new_data[$other_shop_id][] = $value;

        }

        $Dao = M("kfsy_channel_store.kf_channel_product");
        $Dao->startTrans();
        
        foreach ($new_data as $key => $value) {
            
            foreach ($value as $k => $v) {
                $updatePrice = updateChannelProductPrice($this->chnId, $v['store_id'], $v['other_product_id'], array('product_price' => $v['product_price']));

                if($updatePrice == false){
                    $Dao->rollback();
                    unset($value[$k]);
                    continue;
                }
            }
            
            $postData = array();
            foreach ($value as $k1 => $v1) {
                $postData[$k1] = $v1['other_product_id'].':'.$v1['product_price']/100;
            }

            $res = $this->updatePriceBatch($key, $postData);

            if($res['errno'] == '0'){
                $Dao->commit();
                // var_dump($res);
                // var_dump('success');
                // die;
            }else
            {
                $Dao->rollback();
                // var_dump($res);
                // var_dump('error');
                // die;
                return false;
            }

        }
            
        return true;
    }

    /*
        批量同步价格信息
        params
            store_id 店铺id
            price 价格信息对象
    */
    public function updatePriceBatch($store_id = 0, $price = array())
    {
        $BaiDuProductSvc = new BaiDuProductSvc();

        $price = implode(";", $price);
        $data = $BaiDuProductSvc->updatePriceBatch($store_id, $price);

        $res = $BaiDuProductSvc->sendUpdatePriceBatch($data);

        return $res;
    }


    /*
        创建图片对象
        params
            product_info 商品信息对象
    */
    public function createPhoto($product_info = array())
    {
        $res = array();

        $BaiDuProductSvc = new BaiDuProductSvc();

        $picCnt = 4;

        for($i = 1; $i <= $picCnt; $i++){
            $pic = $product_info[sprintf("Pic%d", $i)];

            if(empty($pic)){
                continue;
            }

            $is_master = count($res) < 1 ? "1" : "0";

            $res[] = $BaiDuProductSvc->createPhoto($pic, $is_master);
        }

        return $res;
    }

    /*
        获取远端商品到本地
        params
            store_id 店铺id
    */
    public function pullProduct($store_id = 0)
    {
        $pageSize = 50;
        $page = 1;
        $run = true;

        $BaiDuProductSvc = new BaiDuProductSvc();

        while($run){
            $data = $BaiDuProductSvc->productList($store_id, $page, $pageSize);

            $res = $BaiDuProductSvc->sendProductList($data);

            if($res['errno'] != "0"){
                $run = false;
            }

            $productList = $res['data']['list'];

            foreach ($productList as $key => $value) {
                $this->appendProduct($store_id, $value);
            }
            
            if(count($productList) < $pageSize){
                $run = false;
            }
            $page++;
        }

        return true;
    }

    /*
        追加远程商品到本地
        params
            store_id 店铺id
            data 百度商品数据对象
    */
    public function appendProduct($store_id, $data = array())
    {
        $productId = getProdcutIdByUPC($data['upc']);

        if(empty($productId)){
            return false;
        }

        $product_status = $data['status'] == "1" ? "1" : "2";

        $thumb = array();

        foreach ($data['photos'] as $key => $value) {
            $thumb[] = $value['url'];
        }

        $res = replaceChannelProductInfo($this->chnId, $store_id, $productId, $data['custom_cat_ids'], $data['sku_id'], $data['sale_price'], $data['left_num'], $product_status, $thumb);

        return $res;
    }

    /*
        获取远端分类到本地
        params
            store_id 店铺id
    */
    public function pullCategory($store_id = '')
    {
        $category = $this->getOtherCategoryByBd($store_id);

        if(isset($category['errNo'])){
            return $category;
        }

        $sysCategory = array_flip($GLOBALS['defaultCategory']);

        $addData = array();

        foreach ($category as $key => $value) {
            $tempData = array();
            $tempData['fk_channel_id'] = $this->chnId;
            $tempData['fk_store_id'] = $store_id;
            $tempData['fk_category_id'] = intval($sysCategory[$value['name']]);
            $tempData['other_category_id'] = $value['category_id'];
            $tempData['other_category_name'] = $value['name'];
            $tempData['other_category_rank'] = $value['rank'];
            $tempData['createtime'] = date("Y-m-d H:i:s");

            $addData[] = $tempData;

        }

        $replace = replaceChannelCategory($addData);

        return $replace;

    }
}
?>